﻿/******************************************************/
// WarehousePage プレゼンテーションクラス  
/******************************************************/

using System;
using System.Data;
using System.Globalization;
using System.Resources;
using System.Threading;
using System.Web.UI;
using System.Web.UI.WebControls;
using MAA.Business;
using MAA.Entity;

namespace MAA.Presentation.PRL.Warehouse
{
    public partial class WarehousePage : System.Web.UI.Page
    {
        private ResourceManager rm = new ResourceManager("MAA.Presentation.language", System.Reflection.Assembly.GetExecutingAssembly());
        private CultureInfo m_JapanCulture = new CultureInfo("ja-JP");
        private CultureInfo m_VietnameCulture = new CultureInfo("vi");

        private void UpdateUI()
        {
            langWarehouse.Text = rm.GetString("langWarehouse");
            langAddRiceWare.Text = rm.GetString("langAddRiceWare");
            langRiceType.Text = rm.GetString("langRiceType");
            langAmount.Text = rm.GetString("langAmountNotKg");
            btnAdd.Text = rm.GetString("langAdd");
            langAddPost.Text = rm.GetString("langAddPost");
            lblRiceTypeCreate.Text = rm.GetString("langRiceType");
            langAmount1.Text = rm.GetString("langAmountNotKg");
            RequiredFieldValidator2.Text = rm.GetString("langEnterAmount");
            RangeValidator3.Text = rm.GetString("langNumLimit");
            langMinAmountOrder.Text = rm.GetString("langMinAmountOrder");
            CompareValidator4.Text = rm.GetString("langAmountBuylessthanAmountSell");
            CompareValidator1.Text = rm.GetString("langAmountOrderhigher0");
            langUnitPrice.Text = rm.GetString("langUnitPrice");
            RequiredFieldValidator3.Text = rm.GetString("langEnterPriceBuy");
            RangeValidator2.Text = rm.GetString("langPriceLimit");
            langDifferencePrice.Text = rm.GetString("langDifferencePrice");
            RangeValidator1.Text = rm.GetString("langDifferencePercent");
            langAddressBuy.Text = rm.GetString("langAddressBuy");
            langProvince.Text = rm.GetString("langProvince");
            btnCreate.Text = rm.GetString("langCreate");
            RequiredFieldValidator1.Text = rm.GetString("langEnterAmount");
            dgvWarehouse.Columns[1].HeaderText = rm.GetString("langRiceType");
            dgvWarehouse.Columns[2].HeaderText = rm.GetString("langNumNow");
            dgvWarehouse.Columns[3].HeaderText = rm.GetString("langPriceUpdate");
            dgvWarehouse.Columns[4].HeaderText = rm.GetString("langAllValue");
            dgvWarehouse.Columns[5].HeaderText = rm.GetString("langWarehouseMaxPrice");
            dgvWarehouse.Columns[6].HeaderText = rm.GetString("langWarehouseMinPrice");
            RangeValidator4.Text = rm.GetString("langNumLimit");
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["language"] == null)
            {
                Session["language"] = "vi";
            }
            if (Session["language"].Equals("vi"))
            {
                Thread.CurrentThread.CurrentUICulture = m_VietnameCulture;
                UpdateUI();
            }
            if (Session["language"].Equals("jp"))
            {
                Thread.CurrentThread.CurrentUICulture = m_JapanCulture;
                UpdateUI();
            }
            if (IsPostBack) return;

            //kiem tra da dang nhap chua
            if (Session["userID"] == null)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "popup",
                    "<script type='text/javascript'>alert('" + PRLCommon.ChangeLanguageMessage(Common.MESSAGE_ERROR_NOT_LOGIN) + "');window.location='../HomePage.aspx'</script>");
            }

            //get userID
            long userID = Convert.ToInt64(Session["userID"]);

            //get rice infomation in ware house
            BOLWarehouse bolWh = new BOLWarehouse();
            DataTable tblWh = new DataTable();
            string messageWh = "";
            lblWhMess.Text = null;
            string lang = Session["language"].ToString();
            if (!bolWh.viewWhRice(lang, userID, out tblWh, out messageWh))
            {
                lblWhMess.Text = PRLCommon.ChangeLanguageMessage(messageWh);
            }
            else
            {
                // Neu co du lieu
                if (tblWh != null && tblWh.Rows.Count > 0)
                {
                    dgvWarehouse.DataSource = tblWh;
                    dgvWarehouse.DataBind();
                }
                else
                {
                    lblWhMess.Text = PRLCommon.ChangeLanguageMessage(Common.MESSAGE_NO_DATA_WAREHOUSE);
                    btnCreate.Enabled = false;
                }
            }

            // Get rice type to add
            DataTable typeAdd = new DataTable();
            string messageAdd = "";
            if (!bolWh.viewRiceTypeToAdd(lang,userID, out typeAdd, out messageAdd))
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(),
                    "Alert", "<script>alert('" + PRLCommon.ChangeLanguageMessage(messageAdd) + "')</script>", false);
            }
            else
            {
                // Neu co du lieu
                if (typeAdd != null && typeAdd.Rows.Count > 0)
                {
                    ddlRiceTypeAdd.DataSource = typeAdd;
                    ddlRiceTypeAdd.DataValueField = "ID";
                    ddlRiceTypeAdd.DataTextField = "TypeName";
                    ddlRiceTypeAdd.DataBind();
                    btnAdd.Enabled = true;
                    lblAddError.Text = "";
                }
                else
                {
                    btnAdd.Enabled = false;
                    lblAddError.Text = rm.GetString("langMESSAGE_ERROR_NO_TYPE_TO_ADD");
                }
            }

            // Get rice type to create
            DataTable typeCreate = new DataTable();
            string messageCreate = "";
            if (!bolWh.viewRiceTypeToCreate(lang, userID, out typeCreate, out messageCreate))
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(),
                    "Alert", "<script>alert('" + PRLCommon.ChangeLanguageMessage(messageCreate) + "')</script>", false);
            }
            else
            {
                // Neu co du lieu
                if (typeCreate != null && typeCreate.Rows.Count > 0)
                {
                    btnCreate.Enabled = true;
                    lblCreateError.Text = "";
                }
                else
                {
                    btnCreate.Enabled = false;
                    lblCreateError.Text = rm.GetString("langMESSAGE_ERROR_NO_TYPE_TO_CREATE");
                }
            }
            ddlRiceTypeCreate.DataSource = typeCreate;
            ddlRiceTypeCreate.DataValueField = "ID";
            ddlRiceTypeCreate.DataTextField = "TypeName";
            ddlRiceTypeCreate.DataBind();

            // Get province to add to drop down list
            BOLNews bolNews = new BOLNews();
            DataTable tblProvince = new DataTable();
            string messageProvince = "";
            if (!bolNews.viewProvince(lang, out tblProvince, out messageProvince))
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(),
                    "Alert", "<script>alert('" + PRLCommon.ChangeLanguageMessage(messageProvince) + "')</script>", false);
            }
            ddlProvinceCreate.DataSource = tblProvince;
            ddlProvinceCreate.DataValueField = "ID";
            ddlProvinceCreate.DataTextField = "Name";
            ddlProvinceCreate.DataBind();
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            //get userID
            long userID = Convert.ToInt64(Session["userID"]);
            //get riceID
            int riceID = Convert.ToInt32(ddlRiceTypeAdd.SelectedItem.Value);
            //get amount
            long amount = Convert.ToInt64(tbxAmountAdd.Text.Trim());

            BOLWarehouse bolWh = new BOLWarehouse();
            string message = "";

            if (bolWh.addWhRice(userID, riceID, amount, out message))
            {
                //Refresh
                Response.Redirect(Request.RawUrl);
            }
            else
            {
                // Show pop-up message: message
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(),
                    "Alert", "<script>alert('" + PRLCommon.ChangeLanguageMessage(message) + "')</script>", false);
            }
        }

        protected void btnCreate_Click(object sender, EventArgs e)
        {

            int riceID = Convert.ToInt32(ddlRiceTypeCreate.SelectedItem.Value);

            long amount = Convert.ToInt64(tbxAmountCreate.Text.Trim());

            int minOrderAmount = 0;
            if (!tbxMinCreate.Text.Trim().Equals(""))
            {
                minOrderAmount = Convert.ToInt32(tbxMinCreate.Text.Trim());
            }

            int price = Convert.ToInt32(tbxPriceCreate.Text.Trim());

            short percent = 0;
            if (!tbxPercentCreate.Text.Trim().Equals(""))
            {
                percent = Convert.ToInt16(tbxPercentCreate.Text.Trim());
            }

            string address = tbxAddressCreate.Text.Trim();

            short provinceID = Convert.ToInt16(ddlProvinceCreate.SelectedItem.Value);

            Post post = new Post();
            post.UserID = Convert.ToInt64(Session["userID"]);
            post.RiceID = riceID;
            post.Amount = amount;
            post.MinOrderAmount = minOrderAmount;
            post.Price = price;
            post.PercentPrice = percent;
            post.Address = address;
            post.ProvinceID = provinceID;

            BOLTrading bolTrading = new BOLTrading();
            string message = "";
            if (bolTrading.createPost(post, out message))
            {
                // Redirect to TransactionPage
                Response.Redirect("~/PRL.Trading/TransactionPage.aspx");
            }
            else
            {
                // Show pop-up message: message
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(),
                    "Alert", "<script>alert('" + PRLCommon.ChangeLanguageMessage(message) + "')</script>", false);
            }
        }

        protected bool delete(int riceID)
        {
            //get userID
            long userID = Convert.ToInt64(Session["userID"]);

            BOLWarehouse bolWh = new BOLWarehouse();
            string message = "";

            if (bolWh.deleteWhRice(userID, riceID, out message))
            {
                //Refresh
                Response.Redirect(Request.RawUrl);
                return true;
            }
            else
            {
                //Show error
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(),
                    "Alert", "<script>alert('" + PRLCommon.ChangeLanguageMessage(message) + "')</script>", false);
                return false;
            }
        }

        protected bool edit(int riceID, long amount)
        {
            //get userID
            long userID = Convert.ToInt64(Session["userID"]);

            BOLWarehouse bolWh = new BOLWarehouse();
            string message = "";

            if (bolWh.editWhRice(userID, riceID, amount, out message))
            {
                //Refresh
                Response.Redirect(Request.RawUrl);
                return true;
            }
            else
            {
                //Show error
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(),
                    "Alert", "<script>alert('" + PRLCommon.ChangeLanguageMessage(message) + "')</script>", false);
                return false;
            }
        }

        protected void dgvWarehouse_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            // Retrieve the row index stored in the 
            // CommandArgument property.
            int index = Convert.ToInt32(e.CommandArgument);

            // Retrieve the row that contains the button 
            // from the Rows collection.
            GridViewRow row = dgvWarehouse.Rows[index];

            int riceID = Convert.ToInt32(dgvWarehouse.DataKeys[index].Value);

            Label lblAmount = (Label)row.FindControl("dgvWHlblAmount");
            TextBox tbxAmount = (TextBox)row.FindControl("dgvWHtbxAmount");
            ImageButton btnSave = (ImageButton)row.FindControl("dgvWHbtnSave");
            ImageButton btnCancel = (ImageButton)row.FindControl("dgvWHbtnCancel");

            switch (e.CommandName)
            {
                case "EditAmount":
                    {
                        lblAmount.Visible = false;
                        tbxAmount.Visible = true;
                        // Set text
                        tbxAmount.Text = lblAmount.Text;
                        // Set focus
                        tbxAmount.Focus();
                        //Show hide button
                        dgvWarehouse.Columns[7].Visible = false;
                        dgvWarehouse.Columns[8].Visible = true;
                        dgvWarehouse.Columns[9].Visible = true;
                        btnSave.Visible = true;
                        btnCancel.Visible = true;
                        dgvWarehouse.Columns[10].Visible = false;
                    }
                    break;

                case "SaveEdit":
                    {
                        //Get amount
                        long amount = 0;
                        try
                        {
                            amount = Convert.ToInt64(tbxAmount.Text);
                            if (amount <= 0)
                            {
                                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(),
                                    "Alert", "<script>alert('" + rm.GetString("langNumLimit") + "')</script>", false);
                                return;
                            }
                        }
                        catch
                        {
                            ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(),
                                "Alert", "<script>alert('" + rm.GetString("langMustBePositiveInt") + "')</script>", false);
                            return;
                        }
                        //sua amount trong database
                        if (edit(riceID, amount))
                        {
                            // Set text
                            lblAmount.Text = amount.ToString();
                            //Show hide button
                            dgvWarehouse.Columns[7].Visible = true;
                            dgvWarehouse.Columns[8].Visible = false;
                            dgvWarehouse.Columns[9].Visible = false;
                            btnSave.Visible = false;
                            btnCancel.Visible = false;
                            dgvWarehouse.Columns[10].Visible = true;
                        }
                    }
                    break;

                case "CancelEdit":
                    {
                        lblAmount.Visible = true;
                        tbxAmount.Visible = false;
                        //Show hide button
                        dgvWarehouse.Columns[7].Visible = true;
                        dgvWarehouse.Columns[8].Visible = false;
                        dgvWarehouse.Columns[9].Visible = false;
                        btnSave.Visible = false;
                        btnCancel.Visible = false;
                        dgvWarehouse.Columns[10].Visible = true;
                    }
                    break;

                case "DeleteRice":
                    {
                        delete(riceID);
                    }
                    break;
            }
        }

        protected void dgvWarehouse_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ImageButton btnEdit = (ImageButton)e.Row.FindControl("dgvWHbtnEdit");
                ImageButton btnSave = (ImageButton)e.Row.FindControl("dgvWHbtnSave");
                ImageButton btnCancel = (ImageButton)e.Row.FindControl("dgvWHbtnCancel");
                ImageButton btnDelete = (ImageButton)e.Row.FindControl("dgvWHbtnDelete");

                btnEdit.ToolTip = rm.GetString("langWarehouseEdit");
                btnSave.ToolTip = rm.GetString("langWarehouseSave");
                btnCancel.ToolTip = rm.GetString("langWarehouseCancel");
                btnDelete.ToolTip = rm.GetString("langWarehouseDelete");

                btnDelete.OnClientClick = "return confirm('" + rm.GetString("langConfirmDelete") + "');";
            }
        }
    }
}